<template>
  <el-dialog
    v-model="dialogFormVisible"
    :title="title"
    width="500px"
    @close="close"
  >
    <el-form ref="formRef" label-width="100px" :model="form" :rules="rules">
      <el-form-item v-show="type === 'edit'" label="上级节点">
        <el-select
          v-model="form.parentId"
          clearable
          :disabled="form.parentId === 0"
        >
          <el-option label="默认根节点" :value="0" />
          <el-option
            v-for="item in assetCategoryData"
            :key="item.id"
            :label="item.title"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="分类名称" prop="title" required>
        <el-input
          v-model="form.title"
          style="width: 200px"
          placeholder="请输入资产分类名称"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script>
  import { fetchRootList, doAdd, doEdit } from '@/api/assetCategoryManagement'

  export default defineComponent({
    name: 'AssetCategoryEdit',
    props: {
      type: String,
    },
    emits: ['fetch-data'],
    setup(props, { emit }) {
      const $baseMessage = inject('$baseMessage')
      const state = reactive({
        type: '',
        formRef: null,
        treeData: [],
        defaultProps: {
          children: 'children',
          label: 'title',
        },
        form: {
          title: '',
        },
        rules: {
          title: [
            { required: true, trigger: 'blur', message: '请输入资产分类名称' },
          ],
        },
        assetCategoryData: [],
        dialogFormVisible: false,
        title: '',
      })

      const showEdit = (data) => {
        if (data.type === 'add') {
          state.type = 'add'
          state.title = '添加'
          if (data.row && data.row.id) {
            state.form.parentId = JSON.parse(JSON.stringify(data.row)).id
          }
        } else {
          state.type = 'edit'
          state.title = '编辑'
          state.form = JSON.parse(JSON.stringify(data.row))
        }
        fetchData()
        state.dialogFormVisible = true
      }

      const save = () => {
        state['formRef'].validate(async (valid) => {
          if (valid) {
            try {
              const { id, parentId, title } = state.form
              const params = {
                id,
                parentId: parentId || 0,
                title,
              }
              const res =
                state.title === '添加'
                  ? await doAdd(params)
                  : await doEdit(params)
              $baseMessage(res.msg, 'success', 'vab-hey-message-success')
              emit('fetch-data')
              close()
            } catch (err) {
              console.error(err)
            }
          }
        })
      }

      const close = () => {
        state['formRef'].resetFields()
        state.form = {
          parentName: '',
          parentId: '',
        }
        state.dialogFormVisible = false
      }

      const fetchData = async () => {
        try {
          const { data: data } = await fetchRootList()
          state.assetCategoryData = data
        } catch (err) {
          console.error(err)
        }
      }

      return {
        ...toRefs(state),
        showEdit,
        save,
        close,
      }
    },
  })
</script>
